package cse3311.calendarapp.gui;

import java.net.URLEncoder;
import java.util.GregorianCalendar;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import cse3311.calendarapp.AddEventController;
import cse3311.calendarapp.DeleteEventController;
import cse3311.calendarapp.EditEventController;
import cse3311.calendarapp.EventData;
import cse3311.calendarapp.NotificationReciever;
import cse3311.calendarapp.R;
import cse3311.calendarapp.StorageManager;

public class EditEventActivity extends Activity implements
		DialogInterface.OnClickListener {
	private GregorianCalendar date_m;
	private EventData data_m;
	private NotificationReciever alarm;
	private StringBuilder alarmId = new StringBuilder();
	EditText aliasEditText_m;
	EditText locationEditText_m;
	EditText notesEditText_m;
	EditText reminderEditText_m;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_event);

		final ActionBar actionBar = getActionBar();

		Intent intent = getIntent();

		date_m = (GregorianCalendar) intent.getSerializableExtra("date");
		data_m = (EventData) intent.getSerializableExtra("data");
		alarm = new NotificationReciever();
		alarmId.append(Integer.toString(date_m.get(GregorianCalendar.MONTH)));
		alarmId.append(Integer.toString(date_m
				.get(GregorianCalendar.DAY_OF_MONTH)));
		alarmId.append(Integer.toString(date_m
				.get(GregorianCalendar.HOUR_OF_DAY)));

		aliasEditText_m = (EditText) findViewById(R.id.eventAliasEditText);
		locationEditText_m = (EditText) findViewById(R.id.eventLocationEditText);
		notesEditText_m = (EditText) findViewById(R.id.eventNotesEditText);
		reminderEditText_m = (EditText) findViewById(R.id.eventReminderEditText);

		if (data_m != null) {
			aliasEditText_m.setText(data_m.alias_m);
			locationEditText_m.setText(data_m.location_m);
			notesEditText_m.setText(data_m.notes_m);
			reminderEditText_m.setText(Integer
					.toString(data_m.reminderMinutes_m));

			actionBar.setTitle("Edit Event");
		} else {
			actionBar.setTitle("New Event");
		}
	}

	/**
	 * Backward-compatible version of {@link ActionBar#getThemedContext()} that
	 * simply returns the {@link android.app.Activity} if
	 * <code>getThemedContext</code> is unavailable.
	 */
	@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
	private Context getActionBarThemedContextCompat() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
			return getActionBar().getThemedContext();
		} else {
			return this;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_event, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (data_m != null) {
			MenuItem delete = menu.findItem(R.id.action_delete_event);
			MenuItem directions = menu.findItem(R.id.action_get_directions);
			delete.setVisible(true);
			directions.setVisible(true);
		}

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		String result = "";

		switch (item.getItemId()) {
		case R.id.action_save_event:
			boolean newEvent = (data_m == null);

			if (newEvent) {
				data_m = new EventData();
				data_m.start_m = date_m;
			}

			data_m.alias_m = aliasEditText_m.getText().toString().trim();

			if (data_m.alias_m.isEmpty()) {
				break;
			}

			data_m.location_m = locationEditText_m.getText().toString();
			data_m.notes_m = notesEditText_m.getText().toString();

			try {
				data_m.reminderMinutes_m = Integer.parseInt(reminderEditText_m
						.getText().toString());
			} catch (Exception e) {
				data_m.reminderMinutes_m = 0;
			}

			if (newEvent) {
				result = AddEventController.addEvent(data_m);
			} else {
				result = EditEventController.saveEvent(data_m);
			}

			StorageManager.saveCalendar(getApplicationContext().getFilesDir());

			long reminder = data_m.start_m.getTimeInMillis()
					- (data_m.reminderMinutes_m * 60 * 1000);

			alarm.setEventNotification(this.getApplicationContext(), reminder,
					data_m.alias_m, data_m.notes_m,
					Integer.parseInt(alarmId.toString()));

			finish();
			break;
		case R.id.action_discard_event:
			finish();
			break;
		case R.id.action_delete_event:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure?");
			builder.setPositiveButton("Yes", this);
			builder.setNegativeButton("No", this);
			builder.show();
			break;
		case R.id.action_get_directions:
			String location = "geo:0,0?q=";
			try {
				location += URLEncoder.encode(data_m.location_m, "UTF-8");
			} catch (Exception e) {
				break;
			}
			Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
					Uri.parse(location));
			startActivity(intent);
			break;
		default:
			return super.onOptionsItemSelected(item);
		}

		if (!result.equals("")) {
			Toast toast = Toast.makeText(getApplicationContext(), result,
					Toast.LENGTH_SHORT);
			toast.show();
		}

		return true;
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		switch (which) {
		case Dialog.BUTTON_POSITIVE:
			alarm.cancelEventNotification(this.getApplicationContext(),
					(int) data_m.start_m.getTimeInMillis());

			String result = DeleteEventController.deleteEvent(data_m.id_m);

			StorageManager.saveCalendar(getApplicationContext().getFilesDir());

			Toast toast = Toast.makeText(getApplicationContext(), result,
					Toast.LENGTH_SHORT);
			toast.show();

			finish();
		}

	}
}
